<template>
    <!-- 对话框，父组件点击按钮时触发-->
    <v-dialog v-model="dialog" width="500">
        <!--具名插槽, 解构赋值pros, 解构父组件传递给子组件的数据-->
        <template #activator="{ props }">
            <!-- 定义插槽的内容，将接收到的数据赋值给props-->
            <slot :props="props"></slot>
        </template>
        <v-card v-if="currentData" :title="`${title}收藏夹`">
            <v-divider class="mt-2" />
            <v-card-text>
                <v-text-field label="收藏夹名称" v-model="currentData.name" single-line :variant="'outlined'"></v-text-field>
                <v-text-field label="收藏夹描述" v-model="currentData.description" single-line
                    :variant="'outlined'"></v-text-field>
            </v-card-text>

            <v-card-actions>
                <v-btn color="red" text="删除" @click="deleteFavorite()" v-if="props.editData"></v-btn>
                <v-spacer></v-spacer>
                <v-btn color="blue" text="保存" @click="saveFavorite()"></v-btn>
            </v-card-actions>
        </v-card>
    </v-dialog>
    <v-snackbar v-model="snackbar.show" :color="snackbar.color">
        {{ snackbar.text }}

        <template v-slot:actions>
            <v-btn color="blue" variant="text" @click="snackbar.show = false">
                了解
            </v-btn>
        </template>
    </v-snackbar>
</template>
<script setup>
import { computed, ref, watch } from 'vue';
import { apiRemoveFavorite, apiSaveFavorite } from '../../apis/user/favorites';
const dialog = ref(false)
const props = defineProps({
    editData: {
        type: Object,
        default: null,
    },
    closeEvent: {
        type: Function,
        default: () => { }
    },
    editFlag: {
        type: Boolean,
        default: true,
    }
})

const snackbar = ref({
    text: "",
    show: false
})

const showMessage = (text, color) => {
    snackbar.value = {
        text,
        color,
        show: true
    }
}
const title = computed(() => props.editFlag ? "添加" : "编辑")
const currentData = ref(props.editFlag ? { name: "", description: "" } : props.editData)
const saveFavorite = () => {
    apiSaveFavorite(currentData.value).then(({ data }) => {
        showMessage(data.message, data.state ? 'success' : 'error')
        if (!data.state) {
            return;
        }
        dialog.value = false
    })
}
const deleteFavorite = () => {
    apiRemoveFavorite(currentData.value.id).then(({ data }) => {
        showMessage(data.message, data.state ? 'success' : 'error')
        if (!data.state) {
            return;
        }
        dialog.value = false
    })
}
watch(dialog, (e) => {
    if (!e) {
        props.closeEvent()
    }
})
watch(props, (e) => {

    if (e.editData == null) {
        dialog.value = false
        return;
    } else dialog.value = true

    if (e.editFlag) {
        currentData.value = Object.assign({}, { name: "", description: "" })
    } else{
        currentData.value = Object.assign({}, e.editData)
    }
}, {
    deep: true
})
</script>
